package com.foreveross.chameleon.task;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

import com.foreveross.chameleon.config.ChameleonConfig;
import com.foreveross.chameleon.listener.CheckUpdateListener;
import com.foreveross.chameleon.model.ApplicationInfo;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * @descrption app update task
 * @author zhouzhineng
 *
 */
public class AppSyncCheckUpdateTask extends AsyncTask<String, Integer, Void>{

	private ApplicationInfo mAppInfo;
	private CheckUpdateListener mListener;
	private Throwable error = null;
	private ApplicationInfo mNewAppInfo = null;

	public AppSyncCheckUpdateTask(ApplicationInfo appInfo, CheckUpdateListener listener) {
		this.mAppInfo = appInfo;
		this.mListener = listener;
		
	}
	@Override
	protected void onPreExecute() {
		if(mListener != null) mListener.onCheckStart();
	}
	
	@Override
	protected void onPostExecute(Void result) {
		if (error != null) {
			if(mListener != null) mListener.onCheckError(error);
		} else if (mNewAppInfo != null){
			if(mListener != null) mListener.onUpdateAvaliable(mAppInfo, mNewAppInfo);
		} else {
			if(mListener != null) mListener.onUpdateUnavailable();
		}
	}
	
	@Override
	protected void onCancelled() {
		if(mListener != null) mListener.onCancelled();
	}

	@SuppressLint("NewApi")
	@Override
	protected Void doInBackground(String... params) {
		
		/*final ApplicationInfo currentApplication = mAppInfo;
		if(currentApplication == null) return null;
		AsyncHttpClient httpClient = new AsyncHttpClient();
    	httpClient.addHeader("User-Agent", "Chameleon");
    	httpClient.get(ChameleonConfig.APP_SYNC_URL, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int code, Header[] header, byte[] msg,
					Throwable thrw) {
				// TODO Auto-generated method stub
				Log.e("BSL","what the fucking error about network connecting!");
				throw new RuntimeException("检测更新失败，服务器连接异常，状态码:" + code);
			}

			@Override
			public void onSuccess(int code, Header[] header, byte[] msg) {
				// TODO Auto-generated method stub
				if(code == HttpStatus.SC_OK) {
					String responseString = new String(msg);
					if(!responseString.isEmpty()&&!responseString.equals("{}")) {	
						JSONObject jb;
						try {
							jb = new JSONObject(responseString);
							if(jb.getString("result").equals("error")){
								throw new RuntimeException("检测更新失败");
							}
							
							
							Gson gson=new Gson();
							ApplicationInfo nApp=gson.fromJson(responseString, ApplicationInfo.class);
							if (nApp.getBuild() > currentApplication.getBuild()) {//should greater?
								mNewAppInfo = nApp;
							} else {
								mNewAppInfo = null;
							}
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
				}else {
					Log.e("BSL","what the fucking error about network connecting!");
					throw new RuntimeException("检测更新失败，服务器连接异常，状态码:" + code);
				}
				}
			}
    	});*/
		
		ApplicationInfo currentApplication = mAppInfo;
		if(currentApplication == null) return null;
		final BasicHttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 15 * 1000);
		String updateUrl = ChameleonConfig.APP_SYNC_URL;
		System.out.println("updateUrl:" + updateUrl);
		final HttpClient client = new DefaultHttpClient(httpParameters);
		final HttpGet bundleget = new HttpGet(updateUrl);
		bundleget.setHeader("User-Agent", "Deamon");
		try {
			HttpResponse response = client.execute(bundleget);
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				//parse result
				final String responseString = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
				if(!responseString.isEmpty()&&!responseString.equals("{}")) {
//					{"message":"检测应用更新失败！","result":"error"}
					
					JSONObject jb = new JSONObject(responseString);
					if(jb.getString("result").equals("error")){
						throw new RuntimeException("检测更新失败");
					}
					
					
					Gson gson=new Gson();
					ApplicationInfo nApp=gson.fromJson(responseString, ApplicationInfo.class);
//				if (nApp.getBuild() != currentApplication.getBuild()&&null!=nApp.getBundle()) {//should greater?
					if (nApp.getBuild() > currentApplication.getBuild()) {//should greater?
						mNewAppInfo = nApp;
					} else {
						mNewAppInfo = null;
					}
					//copyNewAppProperties(nApp);
				}
			} else {
				Log.e("BSL","what the fucking error about network connecting!");
				throw new RuntimeException("检测更新失败，服务器连接异常，状态码:" + response.getStatusLine().getStatusCode());
			}
		} catch (Throwable e) {
			Log.e("VersionUpdate", "获取更新失败", e);
			error = new Exception("访问发生错误，请检查网络");
		}
    	return null;
	}
	
	private void copyNewAppProperties(ApplicationInfo newApp) {
		mAppInfo.setMainModuleTag(newApp.getMainModuleTag());
		mAppInfo.setReleaseNote(newApp.getReleaseNote());
		mAppInfo.save(mAppInfo);
	}
}
